package test3.main;

import test3.bean.Employee;
import test3.controller.PageController;
import test3.controller.impl.PageControllerImpl;
import test3.main.Index;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

public class ModifyEmployeeAction implements ActionListener {

	Index index;
	
	public ModifyEmployeeAction(Index in) {
		index = in;
	}

	private PageController controller=new PageControllerImpl();

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		String select = e.getActionCommand();
		if(select == "query") {

			String idStr=index.modifyEmployeeQueryIdText.getText();
			Integer id=null;

			//如果输入为空的处理
			if (idStr!=null)
				id=Integer.parseInt(idStr);
			else{
				JOptionPane.showMessageDialog(null,
						"请输入你要查询的id","Result",JOptionPane.PLAIN_MESSAGE);
				return;
			}
			//按照id号查询一个员工信息
			Employee employee = controller.queryById(id);

			//如果没有查询结果的处理
			if (employee==null) {
				JOptionPane.showMessageDialog(null,
						"Query failure", "Result", JOptionPane.PLAIN_MESSAGE);
				return;
			}
			//显示员工的信息
			index.modifyEmployeeIdText.setText(""+employee.getId());
			index.modifyEmployeeAgeText.setText(""+employee.getAge());
			index.modifyEmployeeNameText.setText(employee.getName());
			if (employee.getSex()==0)
			   index.modifyEmployeeGenderText.setText("女");
			else if (employee.getSex()==1)
				index.modifyEmployeeGenderText.setText("男");


			Toolkit.getDefaultToolkit().beep();
		}
		else if(select == "modify"){

			try {
				//获取控件上的数据
				Integer age = Integer.parseInt(index.modifyEmployeeAgeText.getText());
				Integer sex = null;
				Integer id = Integer.parseInt(index.modifyEmployeeIdText.getText());
				String name = index.modifyEmployeeNameText.getText();
				if (index.modifyEmployeeGenderText.getText().equals("男"))
					sex = 1;
				else if (index.modifyEmployeeGenderText.getText().equals("女"))
					sex = 0;
				//封装员工的信息
				Employee ee = new Employee(id, name, sex, age);
				//添加或者更新数据
				controller.updateOrInsert(ee);
			}catch (Exception eee){
				eee.printStackTrace();
				JOptionPane.showMessageDialog(null,
						"请输入正确的数据！","Result",JOptionPane.PLAIN_MESSAGE);
				return;
			}

			//添加之后的操作

			Toolkit.getDefaultToolkit().beep();
			JOptionPane.showMessageDialog(null, "Modify success","Result",JOptionPane.PLAIN_MESSAGE);
		}
		else{
			index.card.show(index.panel, "welcome");
		}
	}

}
